package cn.geminis.warehouse.service.basic.entity;

import cn.geminis.lowcode.annotation.*;
import cn.geminis.warehouse.service.basic.entity.filter.VendorFilter;
import cn.geminis.warehouse.service.basic.entity.repository.VendorRepository;
import cn.geminis.warehouse.service.util.SpringApplicationContext;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import jakarta.persistence.Column;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@UuidEntity(idFieldAnnotations = {"com.alibaba.excel.annotation.ExcelIgnore"})
@SoftDeleteEntity(deleteFieldAnnotations = {"com.alibaba.excel.annotation.ExcelIgnore"})
@QueryFilter
@CrudRepository
@CrudController
@ExcelController
public class Vendor {
    @Column(nullable = false)
    @ExcelProperty("名称")
    @QueryFilterProperty
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.Like, valueFormat = "%%%s%%")
    private String name;

    @Column(nullable = false)
    @ExcelProperty("地址")
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.Like, valueFormat = "%%%s%%")
    private String address;

    public static class VendorConverter implements Converter<Vendor> {
        @Override
        public Vendor convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
            var name = cellData.getStringValue();
            var repository = SpringApplicationContext.getBean(VendorRepository.class);
            return repository.findOne(VendorFilter.builder().name(name).deleted(false).build()).get();
        }

        @Override
        public WriteCellData<?> convertToExcelData(Vendor value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
            return new WriteCellData<>(value.name);
        }
    }
}
